# cron: 30 22 * * *
# new Env("星芽短剧每日统计")
import os
import re
import json
import glob
from datetime import datetime, timedelta

# ====================== 配置区域 ======================
LOG_DIR_PATTERN = "/ql/data/log/XiaoMao_星芽短剧脚本_*"  # 日志目录模式（支持通配符）
REPORT_FILE = "/ql/data/log/Message/PUSH_XYDJ.log"  # 报告保存路径
HISTORY_FILE = "/ql/data/log/Message/PUSH_XYDJ.json"  # 历史数据保存路径
PUSH_PLUS_TOKEN = os.getenv("PUSH_PLUS_TOKEN")  # 从环境变量获取推送token
CASH_WARNING_THRESHOLD = 15.0  # 可提现超过此值提醒
DEBUG_MODE = os.getenv("DEBUG_MODE", "false").lower() == "true"  # 调试模式开关
# =====================================================

class AccountProcessor:
    def __init__(self):
        self.today = datetime.now().strftime("%Y-%m-%d")
        self.accounts = {}
        self.account_notes = self.load_account_notes()
        self.history = self.load_history()
        self.report_date = ""
        self.total_accounts = 0
        self.success_accounts = 0
        self.failed_accounts = 0
        self.total_gold = 0
        self.total_cash = 0
        self.total_gold_increment = 0
        self.total_withdraw = 0
        self.two_day_data = {}  # 存储两天的账号数据用于提现分析

    def debug_print(self, message):
        """仅在调试模式下打印消息"""
        if DEBUG_MODE:
            print(message)

    def load_account_notes(self):
        """从环境变量加载账号备注"""
        account_notes = {}
        notes_str = os.getenv("PUSH_XYDJ_AN", "")
        if notes_str:
            try:
                pairs = notes_str.split('&')
                for pair in pairs:
                    if '#' in pair:
                        account_id, note = pair.split('#', 1)
                        account_notes[account_id] = note
            except Exception as e:
                self.debug_print(f"⚠️ 账号备注解析错误: {str(e)}")
        return account_notes

    def load_history(self):
        if os.path.exists(HISTORY_FILE):
            try:
                with open(HISTORY_FILE, 'r') as f:
                    return json.load(f)
            except Exception as e:
                self.debug_print(f"⚠️ 历史数据加载错误: {str(e)}")
                return {}
        return {}

    def save_history(self):
        # 只保留最近三天的数据
        if len(self.history) > 3:
            dates = sorted(self.history.keys(), reverse=True)[:3]
            self.history = {date: self.history[date] for date in dates}
        
        try:
            with open(HISTORY_FILE, 'w') as f:
                json.dump(self.history, f, indent=2)
        except Exception as e:
            self.debug_print(f"⚠️ 历史数据保存错误: {str(e)}")

    def find_log_files(self, days=1):
        """查找指定天数内的日志文件，支持嵌套目录结构"""
        log_files = []
        
        # 查找所有匹配的目录
        log_dirs = [d for d in glob.glob(LOG_DIR_PATTERN) if os.path.isdir(d)]
        
        if not log_dirs:
            print(f"⚠️ 未找到匹配的日志目录: {LOG_DIR_PATTERN}")
            return []
        
        self.debug_print(f"📁 找到 {len(log_dirs)} 个日志目录")
        
        # 计算日期范围
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        # 在每个目录中递归查找.log文件
        for log_dir in log_dirs:
            for root, dirs, files in os.walk(log_dir):
                for file in files:
                    if file.endswith('.log'):
                        # 尝试从文件名中提取日期
                        file_date = None
                        date_match = re.search(r'(\d{4}-\d{2}-\d{2})', file)
                        if date_match:
                            try:
                                file_date = datetime.strptime(date_match.group(1), "%Y-%m-%d")
                            except:
                                pass
                        
                        # 如果没有从文件名提取到日期，使用文件修改时间
                        if not file_date:
                            file_path = os.path.join(root, file)
                            file_mtime = os.path.getmtime(file_path)
                            file_date = datetime.fromtimestamp(file_mtime)
                        
                        # 检查文件日期是否在指定范围内
                        if start_date <= file_date <= end_date:
                            log_files.append(os.path.join(root, file))
        
        print(f"📄 找到 {len(log_files)} 个近 {days} 天的日志文件")
        return log_files

    def parse_logs(self):
        # 查找近2天的日志文件
        log_files = self.find_log_files(days=2)
        
        if not log_files:
            print("⚠️ 未找到日志文件")
            return
            
        log_files.sort(key=os.path.getmtime, reverse=True)
        
        # 用于存储所有找到的账号数据，按日期和账号ID组织
        all_accounts_data = {}
        
        for log_file in log_files:
            try:
                self.debug_print(f"🔍 正在处理: {log_file}")
                with open(log_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    
                # 获取日志日期
                date_match = re.search(r'## 开始执行... (\d{4}-\d{2}-\d{2})', content)
                log_date = date_match.group(1) if date_match else None
                
                if not log_date:
                    # 尝试从文件名提取日期
                    file_date_match = re.search(r'(\d{4}-\d{2}-\d{2})', os.path.basename(log_file))
                    if file_date_match:
                        log_date = file_date_match.group(1)
                    else:
                        # 使用文件修改时间作为日期
                        file_mtime = os.path.getmtime(log_file)
                        log_date = datetime.fromtimestamp(file_mtime).strftime("%Y-%m-%d")
                
                if not self.report_date:
                    self.report_date = log_date
                    self.debug_print(f"   📅 设置报告日期为: {self.report_date}")
                
                # 初始化该日期的数据存储
                if log_date not in all_accounts_data:
                    all_accounts_data[log_date] = {}
                
                # 提取账号详情
                account_blocks = re.split(r'⏳ 正在处理第 \d+/\d+ 个账号', content)[1:]
                self.debug_print(f"   🔍 找到 {len(account_blocks)} 个账号区块")
                
                for block in account_blocks:
                    # 提取账号ID
                    account_id_match = re.search(r'【星芽免费短剧账号\d+】(\d+)', block)
                    if not account_id_match:
                        continue
                    account_id = account_id_match.group(1)
                    
                    # 只保留每个账号的最新数据
                    if account_id in all_accounts_data[log_date]:
                        self.debug_print(f"   ⏩ 跳过已处理的账号: {account_id}")
                        continue
                    
                    # 检查账号是否成功
                    if "✅ 账号处理完成" in block or "📋 账号" in block:
                        gold_match = re.search(r'💰目前金币数量: (\d+)', block)
                        cash_match = re.search(r'💰可提现: ([\d.]+)', block)
                        sign_match = "❌签到失败" in block
                        ad_task_match = re.search(r'看视频金币任务(.*?)\((\d+)/(\d+)\)', block)
                        shop_task_match = re.search(r'逛街任务(.*?)\((\d+)/(\d+)\)', block)
                        
                        if gold_match and cash_match:
                            self.debug_print(f"   ✅ 找到账号数据: {account_id}")
                            account_data = {
                                "gold": int(gold_match.group(1)),
                                "cash": float(cash_match.group(1)),
                                "sign_failed": sign_match,
                                "ad_task": f"{ad_task_match.group(2)}/{ad_task_match.group(3)}" if ad_task_match else "0/10",
                                "shop_task": f"{shop_task_match.group(2)}/{shop_task_match.group(3)}" if shop_task_match else "0/7",
                                "gold_increment": 0,
                                "conversion": 0,
                                "withdraw": 0
                            }
                            
                            # 计算预计转换金额
                            account_data["conversion"] = round(account_data["gold"] / 38000, 2)
                            
                            # 存储账号数据
                            all_accounts_data[log_date][account_id] = account_data
                            
            except Exception as e:
                print(f"⚠️ 日志文件处理错误 {log_file}: {str(e)}")
        
        # 如果没有找到当天的数据，使用最近一天的数据
        if self.report_date not in all_accounts_data and all_accounts_data:
            self.report_date = sorted(all_accounts_data.keys(), reverse=True)[0]
            print(f"⚠️ 未找到当天日志，使用最新日志日期: {self.report_date}")
        
        # 处理两天的数据用于提现分析
        self.two_day_data = all_accounts_data
        
        # 提取当天的账号数据
        if self.report_date in all_accounts_data:
            self.accounts = all_accounts_data[self.report_date]
            
            # 计算提现金额和金币增量
            for account_id, data in self.accounts.items():
                # 查找前一天的账号数据
                prev_date = (datetime.strptime(self.report_date, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
                prev_data = None
                
                # 尝试从两天的数据中获取前一天的数据
                if prev_date in all_accounts_data and account_id in all_accounts_data[prev_date]:
                    prev_data = all_accounts_data[prev_date][account_id]
                # 尝试从历史文件中获取前一天的数据
                elif prev_date in self.history and account_id in self.history[prev_date]:
                    prev_data = self.history[prev_date]
                
                if prev_data:
                    # 计算金币增量
                    data["gold_increment"] = data["gold"] - prev_data.get("gold", 0)
                    
                    # 计算提现金额
                    prev_cash = prev_data.get("cash", 0)
                    prev_gold = prev_data.get("gold", 0)
                    
                    # 预期现金 = 前一天现金 + 前一天金币转换金额
                    expected_cash = prev_cash + (prev_gold / 38000)
                    calculated_withdraw = round(expected_cash - data["cash"], 2)
                    
                    # 应用容差规则
                    if abs(calculated_withdraw - round(calculated_withdraw)) <= 0.3:
                        data["withdraw"] = round(calculated_withdraw)
                    else:
                        # 检查是否为0.5的倍数
                        half_multiple = round(calculated_withdraw * 2) / 2
                        if abs(calculated_withdraw - half_multiple) <= 0.3:
                            data["withdraw"] = half_multiple
                
                # 更新统计数据
                self.total_gold += data["gold"]
                self.total_cash += data["cash"]
                self.total_gold_increment += data["gold_increment"]
                self.total_withdraw += data["withdraw"]
        
        # 更新总账号数和成功/失败数（从当天日志中提取）
        if self.accounts:
            self.total_accounts = len(self.accounts)
            # 简化处理：认为所有解析到的账号都是成功的
            self.success_accounts = self.total_accounts
            self.failed_accounts = 0

    def generate_report(self):
        if not self.accounts:
            return "⚠️ 未找到有效的账号数据，跳过报告生成"
        
        # 保存当前数据到历史
        self.history[self.report_date] = {}
        for account_id, data in self.accounts.items():
            self.history[self.report_date][account_id] = {
                "gold": data["gold"],
                "cash": data["cash"]
            }
        self.save_history()
        
        # 生成报告内容
        report = []
        report.append(f"📅 报告日期: {self.report_date}")
        report.append(f"👤 总账号数: {self.total_accounts}个")
        report.append(f"✅ 成功登录: {self.success_accounts}个")
        report.append(f"❌ 登录失败: {self.failed_accounts}个")
        report.append(f"🔄 处理中: 0个")
        report.append(f"💰 总金币量: {self.total_gold}金币")
        report.append(f"📈 总金币增加量: {self.total_gold_increment}金币")
        report.append(f"💵 总现金余额: {self.total_cash:.2f}元")
        report.append(f"💸 今日提现金额: {self.total_withdraw:.2f}元")
        
        # 高现金账号
        high_cash_accounts = []
        for account_id, data in self.accounts.items():
            if data["cash"] >= CASH_WARNING_THRESHOLD:
                note = self.account_notes.get(account_id, "无备注")
                high_cash_accounts.append(f"  账号{len(high_cash_accounts)+1} [{account_id} - {note}]: {data['cash']:.2f}元")
        
        if high_cash_accounts:
            report.append("💰 可提现超过阈值账号:")
            report.extend(high_cash_accounts)
        else:
            report.append("💰 没有可提现超过阈值的账号")
        
        # 账号详情
        report.append("\n📋 账号详情:")
        for i, (account_id, data) in enumerate(self.accounts.items()):
            note = self.account_notes.get(account_id, "无备注")
            report.append(f"🔷 账号{i+1} [{account_id} - {note}]")
            report.append(f"  💰 当前金币: {data['gold']}")
            report.append(f"  💵 现金余额: {data['cash']:.2f}元")
            report.append(f"  💸 今日提现: {data['withdraw']:.2f}元")
            
            # 提现检测信息
            prev_date = (datetime.strptime(self.report_date, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
            prev_cash = 0
            prev_gold = 0
            
            # 尝试从两天的数据中获取前一天的数据
            if prev_date in self.two_day_data and account_id in self.two_day_data[prev_date]:
                prev_cash = self.two_day_data[prev_date][account_id].get("cash", 0)
                prev_gold = self.two_day_data[prev_date][account_id].get("gold", 0)
            # 尝试从历史文件中获取前一天的数据
            elif prev_date in self.history and account_id in self.history[prev_date]:
                prev_cash = self.history[prev_date][account_id].get("cash", 0)
                prev_gold = self.history[prev_date][account_id].get("gold", 0)
            
            # 计算现金变化 - 确保正数表示减少，负数表示增加
            cash_change = prev_cash - data["cash"]
            cash_change_display = f"现金减少: {cash_change:.2f}元" if cash_change > 0 else f"现金增加: {-cash_change:.2f}元"
            
            # 计算预期提现金额
            expected_withdraw = prev_cash + (prev_gold / 38000) - data["cash"]
            
            report.append(f"  ℹ️ 提现检测:")
            report.append(f"    前一天现金: {prev_cash:.2f}元")
            report.append(f"    前一天金币: {prev_gold} (预计转换: {prev_gold/38000:.2f}元)")
            report.append(f"    预期提现金额: {expected_withdraw:.2f}元")
            report.append(f"    实际提现金额: {data['withdraw']:.2f}元")
            report.append(f"    {cash_change_display}")
            
            report.append(f"  ✅ 签到: {'失败' if data['sign_failed'] else '成功'}")
            report.append(f"  ⏱️ 增加时长: 成功0次, 失败0次")
            
            # 修复f-string语法问题
            ad_task_display = '✅ 已完成' if data['ad_task'] == '10/10' else f'🔄 进行中 ({data["ad_task"]})'
            shop_task_display = '✅ 已完成' if data['shop_task'] == '7/7' else f'🔄 进行中 ({data["shop_task"]})'
            
            report.append(f"  📺 看广告任务: {ad_task_display}")
            report.append(f"  🛍️ 逛街任务: {shop_task_display}")
            
            report.append(f"  📈 今日金币增加量: {data['gold_increment']}金币")
            report.append(f"  🔄 当日预计转换金额: {data['conversion']:.2f}元")
            report.append("")
        
        return "\n".join(report)

    def save_report(self, content):
        os.makedirs(os.path.dirname(REPORT_FILE), exist_ok=True)
        with open(REPORT_FILE, 'w', encoding='utf-8') as f:
            f.write(content)

    def push_report(self, content):
        if not PUSH_PLUS_TOKEN:
            print("⚠️ PUSH_PLUS_TOKEN 未设置，跳过推送")
            return False
        
        try:
            import requests
            url = "http://www.pushplus.plus/send"
            headers = {"Content-Type": "application/json"}
            data = {
                "token": PUSH_PLUS_TOKEN,
                "title": f"星芽短剧脚本报告 - {self.report_date}",
                "content": content,
                "template": "txt"
            }
            response = requests.post(url, json=data, headers=headers)
            response.raise_for_status()
            return True
        except Exception as e:
            print(f"⚠️ 推送失败: {str(e)}")
            return False

    def process(self):
        self.parse_logs()
        if not self.report_date:
            print("⚠️ 未找到有效的日志数据")
            return
        
        report_content = self.generate_report()
        self.save_report(report_content)
        
        # 打印报告内容到日志（始终显示）
        print("\n" + "=" * 50)
        print("📊 生成的报告内容:")
        print(report_content)
        print("=" * 50 + "\n")
        
        # 尝试推送报告，失败时重试一次
        if self.push_report(report_content):
            print("✅ 报告推送成功")
        else:
            print("🔄 尝试重新推送报告...")
            if self.push_report(report_content):
                print("✅ 报告推送成功")
            else:
                print("❌ 报告推送失败")
        
        print("✅ 报告处理完成")

if __name__ == "__main__":
    print("=" * 50)
    print(f"🚀 开始处理星芽短剧报告 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    try:
        processor = AccountProcessor()
        processor.process()
    except Exception as e:
        print(f"⚠️ 脚本执行发生严重错误: {str(e)}")
    print(f"🏁 处理完成 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 50)